﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataMining.Bean;
using System.Data.SqlClient;
using DataMining.DataAccess.HospitalDataSetTableAdapters;
using System.Data;
using System.Windows;

namespace DataMining.DataAccess
{
    class MedicalRecordAccess
    {
        public long InsertList(List<Medical_Record> recordlist)
        {
            //通过单例模式获取系统唯一的connection
            MyConnection myconn = new MyConnection();
            SqlConnection connection = myconn.getSqlConnection2();
            connection.Open();

            //设置command
            SqlCommand command = connection.CreateCommand();
            command.CommandText = "select * from Medical_Record";
            //定义Adapter
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);
            adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
            adapter.InsertCommand = commandBuilder.GetInsertCommand();
            adapter.DeleteCommand = commandBuilder.GetDeleteCommand();

            //定义数据Table
            DataTable recordTable = new DataTable("Medical_Record");
            adapter.Fill(recordTable);//装载数据表
            int count = 0;
            //设置TDS的数据库每次提交的数量
            int batchsiza = 10;
            adapter.UpdateBatchSize = batchsiza;
            foreach (Medical_Record record in recordlist)
            {
                count++;
                DataRow row = recordTable.NewRow();
                //通过反射机制填入row中
                RowValueFromDataTable.GetValueFromTable(record, row);
                recordTable.Rows.Add(row);
                //
                if (count % batchsiza == 0)
                {
                    try 
                    {
                        adapter.Update(recordTable);
                    }
                    catch(SqlException ex) 
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally 
                    {
                        recordTable.Clear();
                    }
                    
                    
                }
            }
            adapter.Update(recordTable);
            recordTable.Clear();
            connection.Close();
            return count;
        }
    }
}
